package httpRouter

import (
	"fmt"
	"net/http"
	"httpContext"
	"strings"
)

//路由

type Router struct {
	Method string
	router []routerMap
}

type routerMap struct {
	MethodMap methodMap
}

type methodMap []urlMap

type param struct {
	Key string
	Value string
}

type urlMap struct {
	urlPath string
	Params []param
	urlFunc httpContext.ContextFunc
}

func NewDefault()*Router{
	return new(Router)
}

func(R *Router) ServeHTTP(w http.ResponseWriter,r *http.Request){

	if r.URL.String()[0] != '/'{
		fmt.Println("路由错误")
		http.NotFound(w,r)
		return
	}

	var urlPathString = r.URL.String()


	if R.Method == r.Method{
		for _,v := range R.router{
			for _,vv := range v.MethodMap{
				url_path := strings.Split(urlPathString,"/")
				router_path := strings.Split(vv.urlPath,"/")
				if len(url_path) == len(router_path){//根据 '/'分成的数组个数相同

					//如果路由设置了该url带参数，则最后的/后面不能为空
					if url_path[len(url_path)-1] != "" && router_path[len(router_path)-1] != ""{
						var once_params []httpContext.Param
						for k,v_path := range router_path{
							if strings.Contains(v_path,":"){
								once_params = append(once_params,httpContext.Param{strings.TrimLeft(v_path,":"),url_path[k]})
							}
						}
						vv.urlFunc(&httpContext.Context{w,r,once_params})
					}else if url_path[len(url_path)-1] == "" && router_path[len(router_path)-1] == "" {
						vv.urlFunc(&httpContext.Context{w,r,nil})
					}

				}
			}
		}
	}

}

func(R *Router) GET(url string,conFunc httpContext.ContextFunc){

	once_url := urlMap{url,nil,conFunc}

	once_arr := []urlMap{}
	once_arr = append(once_arr,once_url)

	once := routerMap{once_arr}



	R.router = append(R.router,once)
	R.Method = "GET"
}

func(R *Router) Run(port string){
	http.ListenAndServe(":"+port,R)
}
